package cn.zhf.shop.config;



import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class AccessTokenService {

    private Logger logger=LoggerFactory.getLogger(getClass());

    private  String accessToken=null;

    private  Date expiredTime;

    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    public String getAccessToken(){
        Date now = new Date();
        if (accessToken==null||now.after(expiredTime)){
            logger.info("获取AccessToken，token已过期或不存在，联网获取");
            return getAccessTokenFromWeb(appid,secret);
        }else {
            logger.info("获取AccessToken，token 存在且未过期");
            return accessToken;
        }
    }

    private String getAccessTokenFromWeb(String appId,String secret){
        logger.info("联网获取Access Token");
        Map data=new HashMap<>();
        data.put("appid",appId);
        data.put("secret",secret);
        data.put("grant_type","client_credential");
        String result= HttpRequest.get("https://api.weixin.qq.com/cgi-bin/token")
                .form(data)
                .execute()
                .body();
        logger.info("联网获取Access Token的结果为{}",result);
        JSONObject json= JSONUtil.parseObj(result);
        if(json.getStr("access_token")!=null) {
            //设置过期时间为 110 分钟
            long currentTime = System.currentTimeMillis() + 110 * 60 * 1000;
            expiredTime=new Date(currentTime);
            accessToken = json.getStr("access_token");
            return accessToken;
        }
        return null;
    }
}
